package cn.exrick.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.exrick.common.exception.NeedLoginException;
import cn.exrick.common.exception.XmallException;
import cn.exrick.pojo.TbComment;
import cn.exrick.pojo.TbMember;
import cn.exrick.pojo.TbOrderItem;
import cn.exrick.pojo.common.Result;
import cn.exrick.pojo.dto.ItemDto;
import cn.exrick.pojo.dto.OrderDetail;
import cn.exrick.pojo.front.Member;
import cn.exrick.service.CommentService;
import cn.exrick.service.ItemService;
import cn.exrick.service.LoginService;
import cn.exrick.service.MemberService;
import cn.exrick.service.OrderService;
import cn.exrick.utils.ResultUtil;
import cn.exrick.utils.mybatis.Page;
import cn.exrick.utils.mybatis.PageParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;

@RestController
@Api(description = "评论管理")
public class CommentController {
    @Autowired
    CommentService commentService;
    @Autowired
    ItemService itemService;
    @Autowired
    MemberService memberService;
    @Autowired
    LoginService loginService;
    @Autowired
    OrderService orderService;

    @RequestMapping(value = "/comment/page", method = RequestMethod.GET)
    @ApiOperation(value = "获取商品评论分页")
    public Result<Page<TbComment>> getPage(Long itemId, Long memberId, Double score, String content, Integer pageNo, Integer pageSize) throws Exception {
        if (pageNo == null || pageNo < 0) {
            pageNo = 0;
        }
        if (pageSize == null || pageSize < 0) {
            pageSize = 10;
        }
        PageParam pageParam = new PageParam(pageNo, pageSize);
        Map<String, Object> params = new HashMap<>();
        if (itemId != null) {
            params.put("itemId", itemId);
        }
        if (memberId != null) {
            params.put("memberId", memberId);
        }
        if (score != null) {
            params.put("score", score);
        }
        if (content != null) {
            params.put("content", content);
        }
        Page<TbComment> page = commentService.findPageByCriteria(params, pageParam);
        for (TbComment comment : page.getResult()) {
            TbMember member = memberService.getMemberById(comment.getMemberId());
            comment.setMemberName(member.getUsername());
            comment.setHeader(member.getFile());
        }
        return new ResultUtil<Page<TbComment>>().setData(page);
    }

    @RequestMapping(value = "/comment/list", method = RequestMethod.GET)
    @ApiOperation(value = "获取商品评论列表")
    public Result<List<TbComment>> getPage(Long itemId, Long memberId, Double score, String content) throws Exception {
        Map<String, Object> params = new HashMap<>();
        if (itemId != null) {
            params.put("itemId", itemId);
        }
        if (memberId != null) {
            params.put("memberId", memberId);
        }
        if (score != null) {
            params.put("score", score);
        }
        if (content != null) {
            params.put("content", content);
        }
        List<TbComment> list = commentService.findListByCriteria(params);
        for (TbComment comment : list) {
            TbMember member = memberService.getMemberById(comment.getMemberId());
            if (member != null) {
                comment.setMemberName(member.getUsername());
                comment.setHeader(member.getFile());
            }
        }
        return new ResultUtil<List<TbComment>>().setData(list);
    }

    @Data
    public class CommentVo {
        private String goodId;
        private Double score;
        private String content;
		public String getGoodId() {
			return goodId;
		}
		public void setGoodId(String goodId) {
			this.goodId = goodId;
		}
		public Double getScore() {
			return score;
		}
		public void setScore(Double score) {
			this.score = score;
		}
		public String getContent() {
			return content;
		}
		public void setContent(String content) {
			this.content = content;
		}
    }

    @RequestMapping(value = "/comment/save", method = RequestMethod.POST)
    @ApiOperation(value = "新增商品评论")
    public Result<Object> save(String token, String orderId, String comments) throws Exception {
        if (orderId == null || StringUtils.isEmpty(token) || comments == null || StringUtils.isEmpty(comments)) {
            throw new XmallException("参数错误");
        }
        List<CommentVo> commentVos = new ArrayList<>();
        for (Object o : JSONObject.parseArray(comments)) {
            JSONObject object = (JSONObject) o;
            CommentVo c = new CommentVo();
            c.setGoodId(object.getString("goodId"));
            c.setContent(object.getString("content"));
            c.setScore(object.getDoubleValue("score"));
            commentVos.add(c);
        }
        Member member = loginService.getUserByToken(token);
        if (member == null) {
            throw new NeedLoginException();
        }

        OrderDetail order = orderService.getOrderDetail(orderId);
        if (order == null) {
            throw new XmallException("订单不存在");
        }

        if (order.getTbOrder().getUserId() != member.getId()) {
            throw new XmallException("非法访问");
        }

        if (order.getTbOrder().getStatus() != 3) {
            throw new XmallException("订单状态非法");
        }

        if (order.getTbOrderItem() == null || order.getTbOrderItem().size() != commentVos.size()) {
            throw new XmallException("参数错误");
        }

        for (TbOrderItem orderItem : order.getTbOrderItem()) {
            boolean flag = false;
            for (CommentVo commentVo : commentVos) {
                if (StringUtils.isEmpty(commentVo.getGoodId()) || commentVo.getScore() == null || commentVo.getScore() < 0 || commentVo.getScore() > 5 || commentVo.getContent() == null) {
                    throw new XmallException("参数错误");
                }
                if (commentVo.getGoodId().equals(orderItem.getItemId())) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                throw new XmallException("请评论所有商品");
            }
        }

        for (CommentVo commentVo : commentVos) {
            TbComment pojo = new TbComment();
            pojo.setItemId(Long.parseLong(commentVo.getGoodId()));
            pojo.setMemberId(member.getId());
            pojo.setScore(new BigDecimal(commentVo.getScore()));
            pojo.setContent(commentVo.getContent());
            commentService.save(pojo);
        }

        order.getTbOrder().setStatus(4);
        order.getTbOrder().setEndTime(new Date());
        orderService.update(order.getTbOrder());
        return new ResultUtil<Object>().setData(null);
    }

    @RequestMapping(value = "/sys/comment/update/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "更新商品评论")
    public Result<Object> update(@PathVariable Long id, Long itemId, Long memberId, Double score, String content) throws Exception {
        if (itemId == null || memberId == null || score == null || StringUtils.isEmpty(content)) {
            throw new XmallException("参数错误");
        }
        TbComment pojo = commentService.findById(id);

        if (pojo == null) {
            throw new XmallException("评论不存在");
        }

        ItemDto itemDto = itemService.getItemById(itemId);
        if (itemDto == null) {
            throw new XmallException("商品不存在");
        }

        TbMember member = memberService.getMemberById(memberId);
        if (member == null) {
            throw new XmallException("用户不存在");
        }
        if (itemId != null) {
            pojo.setItemId(itemId);
        }
        if (memberId != null) {
            pojo.setMemberId(memberId);
        }
        if (score != null) {
            pojo.setScore(new BigDecimal(score));
        }
        if (content != null && !content.equals(pojo.getContent())) {
            pojo.setContent(content);
        }
        commentService.update(pojo);
        return new ResultUtil<Object>().setData(true);
    }

    @RequestMapping(value = "/sys/comment/delete/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "更新商品评论")
    public Result<Object> delete(@PathVariable Long id) throws Exception {
        TbComment pojo = commentService.findById(id);

        if (pojo == null) {
            throw new XmallException("评论不存在");
        }
        commentService.delete(pojo);
        return new ResultUtil<Object>().setData(true);
    }
}
